package com.conversationboard.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.database.Database;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;
import com.conversationboard.model.adminlog.AdminLog;

@WebServlet(name = "AdminBanUserFromThread", urlPatterns = "/Admin/AdminBanUserFromThread")
public class AdminBanUserFromThread extends HttpServlet {

	private static final long serialVersionUID = 3838953212669642634L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			int boardId = Integer.parseInt(request.getParameter("boardid"));
			int threadId = Integer.parseInt(request.getParameter("threadid"));
			String loginId = request.getParameter("loginId");

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (!user.isBoardAdmin(boardId)) {
				return;
			}

			/*
			 * Don't let board admins ban other admins of that board or site
			 * admins
			 */

			User toBeBannedUser = User.get(loginId);

			if (toBeBannedUser.isBoardAdmin(boardId)) {
				return;
			}

			Thread thread = Thread.get(boardId, threadId);
			thread.getBannedUsers().put(loginId, loginId);

			User bannedUser = User.get(loginId);

			Connection connection = null;

			try {
				connection = Database.getConnection();
				AdminLog.getInstance().write(connection, user, boardId,
						"User: <strong>" + bannedUser.getDisplayName() + "</strong> has been banned from thread: <strong>" + thread.getTitle() + "</strong> temporarily");
			} finally {
				Database.close(connection);
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/NewAnswersControllerServlet?boardid=" + boardId + "&amp" + threadId);

		} catch (NumberFormatException e) {
		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		}

	}

}
